package com.monitor.admin.util.redis;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

import java.nio.charset.Charset;

/**
 * @Auther: hanhui.liu
 * @Date: 2018/4/27 10:21
 * @Description:
 */
public class FastJsonRedisSerializer<T> implements RedisSerializer<T> {

    private final Charset charset = Charset.forName("UTF8");

    private Class<T> clazz;


    public FastJsonRedisSerializer(Class<T> clazz) {
        this.clazz = clazz;
    }

    @Override
    public byte[] serialize(Object object) throws SerializationException {
        if (object == null) {
            return new byte[0];
        }
        return JSON.toJSONString(object, SerializerFeature.WriteClassName).getBytes(charset);
    }

    @Override
    public T deserialize(byte[] bytes) throws SerializationException {
        if (bytes == null || bytes.length <= 0) {
            return null;
        }
        String str = new String(bytes, charset);
        return (T) JSON.parseObject(str, clazz);
    }
}
